var sitemap, 
	tabPool,
	linkStack,
	scrapedData,
	curTabId,
	curMeta;
	
	

chrome.browserAction.onClicked.addListener(function() {
	//inject content scripts to top document
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
		var tabId = tabs[0].id;
		chrome.tabs.executeScript(tabId, {file: "jquery/jquery-2.1.1.min.js"}, function() {
			chrome.tabs.executeScript(tabId, {file: "jquery/css-selector-generator.js"}, function() {});
			chrome.tabs.executeScript(tabId, {file: "app/SelectTool.js"}, function() {});
			chrome.tabs.executeScript(tabId, {file: "iframe/models.js"}, function() {});
			chrome.tabs.executeScript(tabId, {file: "app/initUI.js"}, function() {});
			chrome.tabs.insertCSS(tabId, {file: "app/website.css", runAt: "document_end"}, function(){});
		});
	});
});

function sendMessage(msg) {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, msg);
  });
}

chrome.tabs.onRemoved.addListener(function (tabId){
	//TODO
});

chrome.runtime.onMessage.addListener(function(msg, source, callback){
	var p = msg.params;
	if(msg.cmd == 'startScrape'){
		startScrape(p);
	}
	else if(msg.cmd == 'log'){
		console.log(p);
	}
	else if(msg.cmd == 'openPage'){
		openPage(p.url, p.sourceIndex, p.pageIndex);
	}
	else if(msg.cmd == 'sendData'){
		receiveData(p.data, p.links, p.meta);
	}
	else if(msg.cmd == 'closeTab'){
		chrome.tabs.remove(tabPool[p]);
	}else{
		sendMessage(msg);
	}
});

chrome.tabs.onUpdated.addListener(function(tabId , info, tab) {
	if (tab.id == curTabId && info.status == "complete") {
		setTimeout(inject, 1000);
    }
})

function receiveData(pageData, links, meta){
	var currentSource = scrapedData[meta.sourceIndex];
	for (var i = 0; i < pageData.length; i++) {
		currentSource.push(pageData[i]);
	}
	linkStack = linkStack.concat(links.reverse());
	link();
}

function link(){
	if(linkStack.length == 0){
		console.log(scrapedData);
	}else{
		var link = linkStack.pop();
		openPage(link.url, link);
	}
}

function startScrape(_sitemap){
	sitemap = _sitemap;
	tabPool = [];
	scrapedData = [];
	linkStack = [];
	for (var i = 0; i < sitemap.pages.length; i++) {
		scrapedData[i] = [];
	}
	//find the start source page
	var startPage = sitemap.pages[0];
	
	//load the start page
	openPage(startPage.url, {
		sourceIndex: 0, //SourcePage在sitemap.pages的位置
		rowIndex: 0, //记录所在的行数或起始行数
	});
}

/*
 * sourceIndex： SourcePage在sitemap.pages的位置
 * pageIndex： 页数，从0开始
 */
function openPage(url, meta){
	curMeta = meta;
	var tab = tabPool[meta.sourceIndex];
	if(tab){
		chrome.tabs.update(tab.id, {url: url, active: false}, function(tab){
			curTabId = tab.id;
		});
	}else{
		chrome.tabs.create({url: url, active: false}, function(tab){
			curTabId = tab.id;
			tabPool[meta.sourceIndex] = tab;
		});
	}
}

function inject(){
	var tabId = curTabId;
	chrome.tabs.executeScript(tabId, {file: "jquery/jquery-2.1.1.min.js"}, function() {
		chrome.tabs.executeScript(tabId, {file: "iframe/models.js"}, function() {
			chrome.tabs.executeScript(tabId, {file: "app/Scraper.js"}, function() {
				chrome.tabs.sendMessage(tabId, {
					sitemap : sitemap,
					meta: curMeta
				});
			});
		});
	});
}
